<?php
/**
 * Хранение лога в БД: сохранение из лог файла и сохранение в БД.
 *
 * @package eventsfetcher
 * @author Alexander Sibiryakov
 **/
class DbStorage
{
	private $sm_db;

	public function __construct(smallDBAL $db) {
		$this->sm_db = $db;
	}

	public function savePurgeLog($file_name) {
		$events = array();

		// загрузим лог
		$handle = fopen($file_name, "a+");

		if (!$handle) return false;
		fseek($handle, 0);
		while (!feof($handle)) {
		    $buffer = fgets($handle, 4096);
			if ($buffer !== false) {
				if ($event = unserialize($buffer)) {

					if (!$this->saveEvent($event)) {
						fclose($handle);
						return false;
					}
					unset($event);
				}
			}
		}
		ftruncate($handle, 0);
		fclose($handle);

		return true;

	}

	private function saveEvent(Event $e) {
		$um = $e->time;
		$type = mysql_escape_string($e->type);
		$openid = mysql_escape_string($e->openid);
		$oid = $e->oid;

		$sql = "INSERT INTO events_stack VALUES(NULL, {$um}, '{$type}', '{$openid}', {$oid})";
		return $this->sm_db->query($sql);
	}

	public function getEvents($um1, $cananonical_url, $limit_count=NULL) {
         // тут вот всем хотелось, чтобы события за последнюю дату отдавались в одном ответе, пришлось написать вот такое условие в WHERE
		$sql = "SELECT events_stack.*, store_objects.type AS content_type FROM events_stack
        INNER JOIN store_objects ON store_objects.oid = events_stack.oid
        WHERE
        events_stack.unixmark >= ".$um1."
        AND
        events_stack.unixmark <= (SELECT max(unixmark) FROM events_stack WHERE unixmark >= ".$um1." ORDER BY unixmark  LIMIT ".($limit_count).")
        AND
        events_stack.type <> 'create_comment_at_item'
        AND
        events_stack.type <> 'create_comment_at_comment'
        ORDER BY events_stack.unixmark";

		/*
		// а вот нормальный sql
		$sql = "SELECT events_stack.*, store_objects.type AS content_type FROM events_stack
		INNER JOIN store_objects ON store_objects.oid = events_stack.oid
		WHERE events_stack.unixmark >= ".$um1.($limit_count ? " ORDER BY events_stack.unixmark LIMIT {$limit_count}" : "");
		*/

		$result = $this->sm_db->query($sql);

		if ($result) {
			$events = array();
			while ($row = mysql_fetch_assoc($result)) {
					$e = new Event ( $row["unixmark"], $row['type'], $row['openid'], $row['oid'] );
					$e->content_type = $row['content_type'];
			        $events[] = $e;
			        $last_um = $row["unixmark"];
			    }
			mysql_free_result($result);


			return $events;
		} else {
			return NULL;
		}

	}

	public function getMaxEventTime() {
		$sql = ' SELECT max( unixmark ) AS last_time FROM `events_stack`';
		$result = $this->sm_db->query($sql);

		$maxEventTime = 0;
		if ($result) {
			while ($row = mysql_fetch_assoc($result)) {
				if ( isset($row['last_time']) && !empty($row['last_time']) ) {
					$maxEventTime = $row['last_time'];
				}
				break;
			}

			mysql_free_result($result);
		}

		return $maxEventTime;
	}

} // END class